<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Service;


use Doctrine\ORM\EntityManager;
use Goods\Entity\GoodsTagGroup;

class GoodsTagGroupManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加标签组
     * @param array $data
     * @return GoodsTagGroup
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addGoodsTagGroup(array $data)
    {
        $tagGroup = new GoodsTagGroup();
        $tagGroup->valuesSet($data);

        $this->entityManager->persist($tagGroup);
        $this->entityManager->flush();

        return $tagGroup;
    }

    /**
     * 编辑标签组
     * @param array $data
     * @param GoodsTagGroup $goodsTagGroup
     * @return GoodsTagGroup
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editGoodsTagGroup(array $data, GoodsTagGroup $goodsTagGroup)
    {
        $goodsTagGroup->valuesSet($data);
        $this->entityManager->flush();

        return $goodsTagGroup;
    }

    /**
     * 删除标签组
     * @param GoodsTagGroup $goodsTagGroup
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteGoodsTagGroup(GoodsTagGroup $goodsTagGroup)
    {
        $this->entityManager->remove($goodsTagGroup);
        $this->entityManager->flush();

        return true;
    }

    /**
     * 批量修改标签组排序
     * @param array $data
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateAllTagGroupSort(array $data)
    {
        foreach ($data['tagGroupSort'] as $key => $value) {
            $tagGroupInfo = $this->entityManager->getRepository(GoodsTagGroup::class)->findOneByTagGroupId($key);
            if($tagGroupInfo) {
                $tagGroupInfo->setTagGroupSort($value);
            }
        }
        $this->entityManager->flush();
        $this->entityManager->clear(GoodsTagGroup::class);
    }
}